package chapter15;

import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author liuziyang
 * @create 2019-03-15 22:32
 */

class Mime {
    public void walkAgainstTheWind() {
    }

    public void sit() {
        System.out.println("pretending to sit");
    }

    public void pushInvisibleWalls() {
    }

    @Override
    public String toString() {
        return "mime";
    }
}

class SmartDog {
    public void speak() {
        System.out.println("woof");
    }

    public void sit() {
        System.out.println("sitting");
    }

    public void reproduce() {
    }
}

class CommunicationReflectively {
    public static void perform(Object speaker) {
        Class<?> spk = speaker.getClass();
        try {
            try {
                Method method = spk.getMethod("speak");
                method.invoke(speaker);
            } catch (NoSuchMethodException e) {
                System.out.println(speaker + " cannot speak");
            }
            try {
                Method method = spk.getMethod("sit");
                method.invoke(speaker);
            } catch (NoSuchMethodException e) {
                System.out.println(speaker + " cannot sit");
            }
        } catch (Exception e) {
            throw new RuntimeException(speaker.toString(), e);
        }
    }
}

public class LatentReflection {
    public static void main(String[] args) {
        CommunicationReflectively.perform(new SmartDog());
        CommunicationReflectively.perform(new Mime());
    }
}
